package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.commons.exception.LyException;
import com.leyou.commons.utils.JsonUtils;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SpecParamMapper;
import com.leyou.item.service.SpecParamService;
import com.leyou.item.service.SpuDetailService;
import com.leyou.item.service.SpuService;
import com.mysql.jdbc.StringUtils;
import com.netflix.discovery.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

@Service
public class SpecParamServiceImpl extends ServiceImpl<SpecParamMapper, SpecParam> implements SpecParamService {
   @Autowired
   private SpuDetailService spuDetailService;
   @Autowired
   private SpuService spuService;
   @Autowired
   private SpecParamService specParamService;
   /**
    * todo:
    * 根据组的id查询所有组下的参数
    */
    @Override
    public List<SpecParamDTO> queryParams(Integer gid, Integer cid, Boolean searching) {
        // 健壮性判断
        if(cid== null && gid == null){
            // 条件不能都为空
            throw new LyException(400, "查询条件不能为空！");
        }
        // 查询
        List<SpecParam> list = query()
                .eq(cid != null, "category_id", cid)
                .eq(gid != null, "group_id", gid)
                .eq(searching != null, "searching", searching)
                .list();
        // 返回
        return SpecParamDTO.convertEntityList(list);
    }
    /**todo:
     * 根据spuId查询spu的所有规格参数值
     *
     */
    @Override
    public List<SpecParamDTO> querySpecvalues(Integer spuId, Boolean searching) {
        //根据商品id查找spudetail
        SpuDetail spuDetail = spuDetailService.getById(spuId);
        //获取json格式的参数键值对
        String specification = spuDetail.getSpecification();
        //把键值对转换成map
        Map<String, Object> specValues = JsonUtils.toMap(specification, String.class, Object.class);
        //先获取categoryid再查询所有参数
        Long cid3 = spuService.getById(spuId).getCid3();
        List<SpecParamDTO> params = specParamService.queryParams(null, Math.toIntExact(cid3), null);
        //找到param的value并存储
        for (SpecParamDTO param : params) {
           String id = String.valueOf(param.getId());
            Object s = specValues.get(id);
            param.setValue(s);
        }
        return params;
    }
}
